/**
 * @filename HuJiaoCommentsController
 *
 * @module
 *
 * @author Justin <zhou78620051@126.com>
 * @version 1
 * @time 2015/10/18 19:00
 */

var request = require("request");
var util = require("util");
var fs = require("fs");

var Logger = require('pomelo-logger').getLogger('HuJiao', 'production');

module.exports = {
  "downloadRes": function (req, res) {
    var appid = req.query.appid;
    var resource = req.query.name || "";

    var resourceNameList;
    if (typeof resource == "string") {
      resourceNameList = resource.split(",");
    } else if (resource instanceof Array) {
      resourceNameList = resource;
    } else {
      resourceNameList = [];
    }

    var url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=%s&media_id=%s";
    var access_token, urlPos;
    WeChatAPIService.getCachedAccessToken(appid, function (err, info) {
      if (err) {
        return res.json({"errcode": 1, "errmsg": "get access token failed"});
      }
      access_token = info.access_token;
      var resourceName;
      for (var i = 0; i < resourceNameList.length; i++) {
        resourceName = resourceNameList[i];
        urlPos = util.format(url, access_token, resourceName);
        //request(urlPos).pipe(fs.createWriteStream(__dirname + '/../../assets/HuJiao/images/' + resourceName));
        request(urlPos).pipe(fs.createWriteStream(__dirname + '/../../.tmp/public/HuJiao/images/' + resourceName));
      }
      res.json({"errcode": 0, "errmsg": "download ok"});
    });
  }
};
